import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";

import Recruit from "./Recruit";
import Resume from "./Resume";
import Subscribe from "./Subscribe";
import RecruitManager from "./RecruitManager";
import Message from "./Message";
import UserCenter from "./UserCenter";
import { useCallback, useEffect } from "react";
import { NavigationProp, useFocusEffect } from "@react-navigation/native";
import { BackHandler, ToastAndroid } from "react-native";
import { useSelector } from "react-redux";
import { BOSS, WORKER } from "../../src/store/reducers/UserRole.ts";

const Tab = createBottomTabNavigator();

type Props = {
  navigation: NavigationProp<ReactNavigation.RootParamList>
}

const Main = (props: Props) => {


  let backClickCount = 0;
  const handleBackPress = useCallback(() => {
    // 在这里编写您的返回事件处理逻辑
    // 返回 true 表示拦截返回事件，返回 false 表示不拦截返回事件
    backClickCount++;
    if (backClickCount < 2) {
      ToastAndroid.show("再点一次，退出应用", ToastAndroid.SHORT);
      setTimeout(() => {
        backClickCount--;
      }, 1000);
    } else {
      props.navigation.goBack();
    }
    return true;
  }, []);

  useFocusEffect(
    useCallback(() => {
      BackHandler.addEventListener("hardwareBackPress", handleBackPress);

      return () => {
        BackHandler.removeEventListener(
          "hardwareBackPress",
          handleBackPress
        );
      };
    }, [handleBackPress])
  );

  useEffect(() => {
    console.log('render');
  }, []);

  const userRole = useSelector(state => state.userRole.userRole);

  return (
    <Tab.Navigator screenOptions={{ headerShown: false }}>
      <Tab.Screen name="找活干" component={Recruit} />
      <Tab.Screen name="找工人" component={Resume} />
      {
        userRole == WORKER && <Tab.Screen name="订阅好活" component={Subscribe} />
      }
      {
        userRole == BOSS && <Tab.Screen name="管理招工" component={RecruitManager} />
      }
      <Tab.Screen name="消息中心" component={Message} />
      <Tab.Screen name="用户中心" component={UserCenter} />
    </Tab.Navigator>
  );
};


export default Main;
